package com.dkha.server.controllers;

import com.dkha.common.enums.ApiUrlEnum;
import com.dkha.common.modules.vo.camera.BayOnetCameraVO;
import com.dkha.common.modules.vo.camera.CameraInfoVO;
import com.dkha.common.modules.vo.camera.PeopleComparableVO;
import com.dkha.common.modules.vo.camera.PeopleVO;
import com.dkha.common.modules.vo.face.ApiFaceSearchReturnVO;
import com.dkha.common.modules.vo.face.ApiFaceSearchVO;
import com.dkha.common.modules.vo.face.FaceTrackVO;
import com.dkha.common.modules.vo.face.PageVO;
import com.dkha.common.redis.RedisKeys;
import com.dkha.common.redis.RedisUtils;
import com.dkha.common.result.CommonResult;
import com.dkha.common.systemcode.SystemCode;
import com.dkha.common.util.DateUtils;
import com.dkha.common.util.TimeUtil;
import com.dkha.common.systemcode.SystemCode;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.modules.entities.FaceCameraEntity;
import com.dkha.server.modules.entities.FaceTrackEntity;
import com.dkha.server.services.FaceCameraService;
import com.dkha.server.services.FaceTrackService;
import com.dkha.server.services.IControlBayonetMidService;
import com.dkha.server.services.impl.TrackTaskImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.jndi.toolkit.url.UrlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version V1.0
 * @Description: TODO(please write your description)
 * All rights 成都电科慧安
 * @Title: TrackController
 * @Package com.dkha.server.controllers
 * @author: panhui
 * @date: 2020/1/13 18:02
 * @Copyright: 成都电科慧安
 */
@RestController
@RequestMapping(value = "/track")
@Api(tags = "轨迹分析")
@Slf4j
public class TrackController extends CommonResult {


    @Autowired
    private Gson gson;

    @Autowired
    private FaceTrackService faceTrackService;
    @Autowired
    private FaceCameraService faceCameraService;

    @GetMapping("/people/{idPortrait}")
    @ApiOperation(value = "根据人脸id查询当前数据")
    public CommonResult getPeopeTrack(@PathVariable("idPortrait") String idPortrait) {
        //查询出唯一的数据
        if (UtilValidate.isEmpty(idPortrait)) {
            return failResult("参数不能为空");
        }
        List<PeopleVO> peopleVOS = new ArrayList<>();
        String time = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        List<PeopleVO> list = trackTask.getRedisPeopleInfo(time, idPortrait);
        if (UtilValidate.isNotEmpty(list)) {
            peopleVOS.addAll(list);
        }
        //把数据库中的json转换为实体类数据
        FaceTrackEntity faceTrackEntity = faceTrackService.queryByIdPortrait(idPortrait);
        if (UtilValidate.isNotEmpty(faceTrackEntity)) {
            List<PeopleVO> peopleVOList = gson.fromJson(faceTrackEntity.getLinkedData(), new TypeToken<List<PeopleVO>>() {
            }.getType());
            peopleVOS.addAll(peopleVOList);
        }
        if (UtilValidate.isEmpty(peopleVOS)) {
            return successResult(new ArrayList<>());
        }
//        for (PeopleVO peopleVO : peopleVOS) {
//            peopleVO.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(peopleVO.getTimestamp()));
//        }
        return successResult(peopleVOS);
    }

    @DeleteMapping("/people/{idPortrait}/{esId}")
    @ApiOperation(value = "删除错误的信息")
    public CommonResult deletePeopeTrack(@PathVariable("idPortrait") String idPortrait, @PathVariable("esId") String esId) {
        //查询出唯一的数据
        if (UtilValidate.isEmpty(idPortrait)) {
            return failResult("参数不能为空");
        }
        //把数据库中的json转换为实体类数据
        FaceTrackEntity faceTrackEntity = faceTrackService.queryByIdPortrait(idPortrait);
        if (UtilValidate.isEmpty(faceTrackEntity)) {
            return successResult(null);
        }
        List<PeopleVO> peopleVOS = gson.fromJson(faceTrackEntity.getLinkedData(), new TypeToken<List<PeopleVO>>() {
        }.getType());
        log.error("处理后{}", peopleVOS.size());
        if (UtilValidate.isEmpty(peopleVOS)) {
            return successResult(null);
        }
        Iterator<PeopleVO> iterator = peopleVOS.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getEsId().equals(esId)) {
                iterator.remove();
            }
        }
        if (peopleVOS.size() > 0) {
            faceTrackEntity.setCharacterData(gson.toJson(peopleVOS.get(0)));
        }
        faceTrackEntity.setLinkedData(gson.toJson(peopleVOS));
        faceTrackService.updateById(faceTrackEntity);
        log.error("处理后{}", peopleVOS.size());
        return successResult(SystemCode.DELETE_SUCCESS.des);
    }


    @Autowired
    private TrackTaskImpl trackTask;

//    @GetMapping("/people/test")
//    @ApiOperation(value = "测试")
//    public CommonResult test(String starTime, String stopTime) {
//
//        String time = "2020-01-14";
////        trackTask.setBingDataCamerID(time);
//        Date date=new Date();
//
//        date.setDate(date.getDate()-1);
//        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
////        String startTime = "2020-01-01", stopTime = "2020-02-02";
////        for(int i=0;i<30+1;i++)
////        {
////
////        }
////        System.out.println(DateUtils.dayDiff(DateUtils.str2Date(starTime, new SimpleDateFormat("yyyy-MM-dd")), DateUtils.str2Date(stopTime, new SimpleDateFormat("yyyy-MM-dd"))));
//        return null;
//    }


    @PostMapping("/people/track")
    @ApiOperation(value = "获取轨迹信息")
    public CommonResult getTrack(@RequestBody FaceTrackVO faceTrackVO) {

        if (UtilValidate.isEmpty(faceTrackVO) || UtilValidate.isEmpty(faceTrackVO.getStartTime()) || UtilValidate.isEmpty(faceTrackVO.getEndTime()) || UtilValidate.isEmpty(faceTrackVO.getUrl()) || UtilValidate.isEmpty(faceTrackVO.getTrajectoryThreshold())) {
            return failResult(SystemCode.ParaIsNull);
        }
        if (UtilValidate.isNotEmpty(faceTrackVO.getTrajectoryThreshold())) {
            faceTrackVO.setTrajectoryThreshold(faceTrackVO.getTrajectoryThreshold() / 100);
        }
   /*     {
            "endTime": "2020-01-14",
                    "startTime": "2020-01-14",
                    "trajectoryThreshold": 80.0,
                    "url": "http://10.51.10.201:9001/middleware/20200114/camera/1578962105682-886.jpg"
        }*/


        //判断是否是否今天
        //如果今天就直接读取redis
        //如果不是今天就读取历史
        //如果包含今天或者历史就需要把所有数据读取出来分析
//        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis());
        String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        List<PeopleVO> peopleVOS = new ArrayList<>();
        List<String> libList = new ArrayList<>();
        //表示包含今天需要从redis读取
        //读取redis和数据库中所有需要比对的库id
//        if (faceTrackVO.getStartTime().equals(nowTime) && faceTrackVO.getEndTime().equals(nowTime)) {
//            //只读取redis所有的数据
//            libList = trackTask.getRedisLibId(nowTime);
//        } else {
        //读取数据库和redis数据
        if (faceTrackVO.getStartTime().equals(nowTime) || faceTrackVO.getEndTime().equals(nowTime)) {
            libList = trackTask.getRedisLibId(nowTime);
        }
        List<String> dbLibList = faceTrackService.findIdFatoryByTime(faceTrackVO);
        if (UtilValidate.isNotEmpty(dbLibList)) {
            libList.addAll(dbLibList);
        }
//        }
        //进行人脸库比对、
        List<String> compareIds = trackTask.faceCheck(faceTrackVO.getUrl(), libList, faceTrackVO.getTrajectoryThreshold());
        if (UtilValidate.isEmpty(compareIds)) {
            return successResult(peopleVOS);
        }
        //先获取redis里面的数据，因为当天的数据不会放在数据库中 209
        //67
        compareIds.forEach(e ->
        {
            List<PeopleVO> peopleVOList = trackTask.getRedisPeopleInfo(nowTime, e);
            if (UtilValidate.isNotEmpty(peopleVOList)) {
                peopleVOS.addAll(peopleVOList);
            }
        });

        //根据id查询数据
        List<FaceTrackEntity> trackList = faceTrackService.findTrackByFaceId(compareIds);
        //获取redis中的人脸数据 211  214
        if (UtilValidate.isNotEmpty(trackList)) {
            trackList.forEach(e ->
            {
                try {
                    List<PeopleVO> list = new ArrayList<>();
                    if (UtilValidate.isEmpty(e.getLinkedData()) || e.getLinkedData().equals("[]")) {
                        list = gson.fromJson(e.getCharacterData(), new TypeToken<List<PeopleVO>>() {
                        }.getType());
                    } else {
                        list = gson.fromJson(e.getLinkedData(), new TypeToken<List<PeopleVO>>() {
                        }.getType());
                    }
                    peopleVOS.addAll(list);
//                    peopleVOS.add(gson.fromJson(e.getLinkedData(), PeopleVO.class));
                } catch (Exception e1) {
                    e1.printStackTrace();
                    System.out.println(e1.getMessage());
                }
            });
        }
        if (UtilValidate.isEmpty(peopleVOS)) {
            return successResult(peopleVOS);
        }
        //将数据进行清洗，返回最终的人脸轨迹数据。按照时间绑定list  list里面的数据如果那个人每更换摄像头
        //轨迹，那个轨迹只有当前一条，如果那人更换摄像头就会加入一条新摄像头里面的轨迹211
        Map<String, List<PeopleComparableVO>> myMap = trackTask.filterPeople(peopleVOS);
        if (UtilValidate.isEmpty(myMap)) {
            return successResult(new HashMap<>());
        }
        //数据筛选 按天进行分组、然后在筛选
//        trackList
        List<PeopleComparableVO> listPop = new ArrayList<>();
        if (UtilValidate.isNotEmpty(myMap)) {
            int dayNum = 0;
            if (faceTrackVO.getStartTime().equals(nowTime) && faceTrackVO.getEndTime().equals(nowTime)) {
                dayNum = 1;
            } else {
                dayNum = DateUtils.dayDiff(DateUtils.str2Date(faceTrackVO.getStartTime(), new SimpleDateFormat("yyyy-MM-dd")), DateUtils.str2Date(faceTrackVO.getEndTime(), new SimpleDateFormat("yyyy-MM-dd")));

            }

            for (int i = 0; i < dayNum + 1; i++) {
                Date date = DateUtils.str2Date(faceTrackVO.getStartTime(), new SimpleDateFormat("yyyy-MM-dd"));
                date.setDate(date.getDate() + i);
                String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
                if (myMap.containsKey(time)) {
                    if (UtilValidate.isNotEmpty(myMap.get(time))) {
                        listPop.addAll(myMap.get(time));
                    }
                }
            }
//            } else {
//                if (myMap.containsKey(nowTime)) {
//                    if (UtilValidate.isNotEmpty(myMap.get(nowTime))) {
//                        listPop.addAll(myMap.get(nowTime));
//                    }
//                }
//            }
        }
        //根据摄像头id查询对应的摄像头信息
        if (UtilValidate.isNotEmpty(listPop)) {

            for (PeopleComparableVO pc : listPop) {
                try {
                    CameraInfoVO cameraInfoVO = faceCameraService.selectFaceCameraID(pc.getCameraId());
                    if (UtilValidate.isNotEmpty(cameraInfoVO)) {
                        pc.setCameraInfoVO(cameraInfoVO);
                    } else {

                    }
                } catch (Exception e) {

                }
            }
        }
        return successResult(listPop);
    }

}
